<template>
  <div class="login" v-if="this.$store.state.isShow === true">
    <div class="login-header">
      <div class="header-left">登录</div>
      <div class="header-right" @click="editIsShow">
        <span @click="xClick(0)"> X </span>
      </div>
    </div>
    <!-- 二维码身体1 -->
    <div
      class="login-body"
      v-if="
        check === true ||
        loginData.code === 801 ||
        loginData.code === 800 ||
        loginData.code === 803 ||
        this.$store.state.changeItem1 === 0
      "
    >
      <!-- 身体左 -->
      <div class="body-left">
        <img
          src="https://s2.music.126.net/style/web2/img/qr_guide.png?f57871ef9b9bf3ed4755624785983e7d"
          alt=""
        />
      </div>
      <!-- 身体右 -->
      <div class="body-right">
        <div class="dl">扫码登录</div>
        <div class="check" v-if="loginData.code === 800">
          <div class="ok">
            <div>二维码已过期</div>
            <button @click="reFresh">点击刷新</button>
          </div>
        </div>
        <img :src="qrimg" alt="" />
        <p>使用<a href="javascript:;">网易云音乐APP</a>扫码登录</p>
      </div>
    </div>

    <!-- 二维码身体二 -->
    <div class="login-body" v-else-if="loginData.code === 802">
      <div class="success"></div>
      <p>扫描成功</p>
      <p>请在手机上确定登录</p>
    </div>

    <!-- <login-item v-if="this.$store.state.changeItem1 === 1"></login-item> -->
    <div class="login-body" v-if="this.$store.state.changeItem1 === 1">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleFormRef"
        label-width="10px"
        class="demo-ruleForm"
        size="medium"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="ruleForm.phone"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
            placeholder="请输入密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-checkbox v-model="checked" size="mini">记住密码</el-checkbox>
        <el-button type="primary" @click="loginByPhone">登录</el-button>
      </el-form>
    </div>

    <div class="footer">
      <div @click="changeItem(1)" v-if="this.$store.state.changeItem1 === 0">
        选择其它方式登录
      </div>
    </div>
  </div>
  <!-- 头 -->
</template>

<script>
import {
  getkey,
  getCode,
  getCheck,
  loginRefresh,
  loginByPhone
} from '@/api/api.js'
// import LoginItem from "./components/loginItem.vue";
// import bus from '@/utils/bus.js'
export default {
  name: 'Login',
  components: {
    // LoginItem,
  },
  data() {
    // /^[1]+[0-9]{10}$/
    // /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    let checkPhone = (rule, value, callback) => {
      if (value) {
        let rgx = /^[1]+[0-9]{10}$/
        if (value.match(rgx) == null) {
          return callback(new Error('请输入正确手机号'))
        } else {
          callback()
        }
      } else if (value === '') {
        callback(new Error('电话不能为空'))
      }
    }
    // 密码
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'))
      }
    }
    return {
      qrurl: '',
      qrimg: '',
      loginData: {},
      isLogin: false,
      check: true,
      // 电话密码
      ruleForm: {
        phone: window.localStorage.getItem('phone') ?? '',
        password: window.localStorage.getItem('password') ?? ''
      },
      // 规则
      rules: {
        phone: [{ validator: checkPhone, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }]
      },
      // 用户信息
      profile: {},
      checked: true
    }
  },
  mounted() {
    this.getKeys()
  },
  methods: {
    xClick(index) {
      this.$store.commit('editChangeItem1', index)
    },
    editIsShow() {
      this.$store.commit('editIsShow')
    },
    // 得到二维码key
    getKeys() {
      try {
        if (this.$store.state.changeItem1 === 0) {
          return getkey().then((res) => {
            this.$store.commit('editUnikey', res.data.unikey)
            // console.log(res);
            // console.log(this.$store.state.unikey)
            this.getCode(this.$store.state.unikey)
          })
        }
      } catch (err) {
        // console.log(err)
      }
    },
    //  二维码生成接口
    async getCode(unikey) {
      try {
        const res = await getCode(unikey)
        // console.log(res);
        this.qrurl = res.data.qrurl
        this.qrimg = res.data.qrimg
        this.getCheck(this.$store.state.unikey)
      } catch (err) {
        console.log(err)
      }
    },
    // 二维码检测扫码状态
    async getCheck(unikey) {
      try {
        const res = await getCheck(unikey)
        // console.log(res);
        if (this.$store.state.changeItem1 === 0) {
          this.loginData = res
          this.isLogin = true
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 点击刷新
    reFresh() {
      this.loginData.code = 801
      this.getKeys()
    },
    // 点击其他方式登录
    changeItem(index) {
      this.$store.commit('editChangeItem1', index)
      this.loginData = {}
      this.check = false
    },
    // 点击登录
    async loginByPhone() {
      // console.log(this.$store.state.changeItem1)
      // this.$refs.ruleFormRef.validate(async (valid) => {
      //   if (!valid) {
      //     return
      //   }
      console.log(1)
      const res = await loginByPhone(this.ruleForm)
      if (res.code !== 200) {
        return this.$message.error(`${res.message}`)
      }
      if (this.checked === true) {
        window.localStorage.setItem('phone', this.ruleForm.phone)
        window.localStorage.setItem('password', this.ruleForm.password)
      } else if (this.checked === false) {
        window.localStorage.removeItem('phone', this.ruleForm.phone)
        window.localStorage.removeItem('password', this.ruleForm.password)
      }

      console.log(res)
      this.$message.success('登录成功')
      this.$store.commit('setCookie', res.cookie)
      this.$store.dispatch('saveToken', res.token)
      this.profile = res.profile
      //  bus.$emit('sendBybus', this.profile)
      this.$store.dispatch('saveUserDetail', res.profile)
      this.$store.commit('editIsShow')
      // this.loginStatus()
      window.location.reload()

      // console.log(this.$store.state);

      // })
      //   const res = await loginByPhone(this.ruleForm);
      // console.log(res);
      // if (res.code !== 200) {
      //   this.$message.error(`${res.message}`);
      // }
      // })
    }
  },
  watch: {
    isLogin: function () {
      let timer = setInterval(async () => {
        this.getCheck(this.$store.state.unikey)
        let code = this.loginData.code
        if (code === 800) {
          console.log('二维码过期')
        } else if (code === 801) {
          // console.log("等待扫码");
          if (
            this.$store.state.changeItem1 === 1 ||
            this.$store.state.isShow === false
          ) {
            clearInterval(timer)
          }
        } else if (code === 802) {
          this.check = false
          console.log('待确认')
        } else if (code === 803) {
          //用户登录成功后清除定时器
          console.log('授权登录成功')
          this.$message.success('登录成功')
          this.$store.commit('setCookie', this.loginData.cookie)
          this.$store.commit('editIsShow')

          loginRefresh()
          window.location.reload()
          clearInterval(timer)
        }
      }, 5000)
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 530px;
  height: 372px;
  position: fixed;
  box-shadow: 0 5px 16px rgb(0 0 0 / 80%);
  // margin: auto;
  top: 140px;
  left: 440px;
  z-index: 999;
  // margin-top: -182px;
  // margin-left: -265px;

  .login-header {
    height: 38px;
    width: 100%;
    background-color: #2d2d2d;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .header-left {
      height: 100%;
      font-size: 14px;
      color: #fff;
      line-height: 38px;
      margin-left: 10px;
    }
    .header-right {
      color: #fff;
      margin-right: 10px;
      &:hover {
        cursor: pointer;
        color: #ccc;
      }
    }
  }
  .login-body {
    height: 280px;
    width: 100%;
    background-color: #fff;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .body-left {
      img {
        width: 125px;
        height: 220px;
      }
    }
    .body-right {
      width: 200px;
      height: 205px;
      position: relative;
      .dl {
        width: 200px;
        height: 24px;
        text-align: center;
        font-size: 18px;
        margin-left: -30px;
      }
      .check {
        position: absolute;
        top: 43px;
        left: 9px;
        width: 120px;
        height: 120px;
        text-align: center;
        // line-height: 138px;
        background: chartreuse;
        // opacity: 0.5;
        background: rgba(255, 255, 255, 0.8);
        .ok {
          margin-top: 30%;

          button {
            width: 66px;
            height: 26px;
            background: linear-gradient(180deg, #81dd81 0%, #55a055 100%);
            border: 1px solid #5baf5b;
            box-shadow: inset 0 -1px 1px 1px rgb(185 230 185 / 31%);
            color: #fff;
            font-size: 12px;
            &:hover {
              cursor: pointer;
            }
          }
        }
      }
      img {
        width: 138px;
        height: 138px;
        margin-top: 10px;
      }
      p {
        width: 200px;
        height: 17px;
        margin-left: -10px;
        margin-top: 10px;
        a {
          text-decoration: none;
          color: #0b6ab2;
          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
    .success {
      width: 140px;
      height: 140px;
      background: url('../../assets/img/suc-icon.png');
    }
  }
  .footer {
    height: 64px;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    // margin-top: -10px;
    div {
      width: 120px;
      height: 30px;
      border: 1px solid #000;
      border-radius: 20px;
      text-align: center;
      line-height: 30px;
      &:hover {
        cursor: pointer;
      }
    }
  }
}
.el-form {
  .el-checkbox {
    display: block;
    margin-left: 13px;
    margin-top: -5px;
    padding-bottom: 5px;
  }
  .el-button {
    width: 210px;
    height: 32px;
    margin-left: 13px;
    line-height: 10px;
  }
}
</style>
